package com.atguigu.crowd.mvc.config;

import com.atguigu.crowd.util.CrowdConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//表示是配置类
@Configuration
//启用web环境下权限控制功能
@EnableWebSecurity

@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebAppSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public BCryptPasswordEncoder getPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder builder) throws Exception {

        //临时使用内存版登录模式测试代码
        //auth.inMemoryAuthentication().withUser("tom").password("123456").roles("ADMIN");

        //正式功能中使用基于数据库的登录认证
        builder.userDetailsService(userDetailsService).passwordEncoder(getPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity security) throws Exception {

        security
                .authorizeRequests()
                .antMatchers("/admin/to/login/page.html","/bootstrap/**","/crowd/**","/css/**","/fonts/**","/ima/**","/jquery/**","/layer/**","/script/**","/ztree/**")
                .permitAll()
                .antMatchers("/admin/get/page")
//                .hasRole("经理")
                .access("hasRole('经理') OR hasAuthority('user:get')")
                .anyRequest()  //其他任意的请求
                .authenticated()  //需要认证
                .and()
                .exceptionHandling()
                .accessDeniedHandler(new AccessDeniedHandler() {
                    @Override
                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
                        request.setAttribute("exception",new Exception(CrowdConstant.MESSAGE_ACCESS_DENIED));

                        request.getRequestDispatcher("/WEB-INF/error.jsp").forward(request, response);
                    }
                })
                .and()
                .csrf()
                .disable()
                .formLogin()   //开启表单登录功能
                .loginPage("/admin/to/login/page.html") //登录页面
                .loginProcessingUrl("/security/do/login")  //处理登录请求
                .defaultSuccessUrl("/admin/to/main/page")  //登录成功后去哪
                .usernameParameter("loginAcct") //账号参数
                .passwordParameter("userPswd")  //密码参数
                .and()
                .logout()  //开启退出登录功能
                .logoutUrl("/security/do/logout") // 指定退出登录的地址
                .logoutSuccessUrl("/admin/to/login/page.html")  // 指定退出登录成功之后去的地址
                ;

    }
}
